package com.wtz.temp.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * Date: 2020/9/21
 * Company: www.dtstack.com
 *
 * @author tiezhu
 */
public class HbaseAPI {
    public static void main(String[] args) throws IOException {
        Connection hbaseConn = getConnection();
    }

    private static Connection getConnection() throws IOException {
        // 可以自定义配置，也可以通过读取配置文件获取相关配置
        Configuration hbaseConf = HBaseConfiguration.create();
        hbaseConf.set("hbase.zookeeper.property.clientPort", "2181");
        hbaseConf.set("hbase.zookeeper.quorum", "kerberos01,kerberos02,kerberos03");
        hbaseConf.set("hbase.master", "kerberos01\\:60010");
        return ConnectionFactory.createConnection(hbaseConf);
    }

    private static void createTable(Connection hbaseConn, String tableName) throws IOException {
        Admin admin = hbaseConn.getAdmin();
        TableName table = TableName.valueOf(tableName);
        if (!admin.tableExists(table)) {
            // 表描述器构造器
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(table);
            // 列族 info 描述器构造器
            ColumnFamilyDescriptorBuilder info = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"));
            // 获取列的描述器
            ColumnFamilyDescriptor columnFamilyDescriptor = info.build();
            // 向表描述器添加列族
            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
            // 获取表的描述器
            TableDescriptor tableDescriptor = tableDescriptorBuilder.build();
            // 通过admin创建表
            admin.createTable(tableDescriptor);
        } else {
            throw new RuntimeException("table exist! ");
        }
        // 关闭hbase连接
    }
}
